<template>
  <a-tree
    checkable
    :defaultExpandAll="defaultExpandAll"
    v-model="checkedKeys"
    :selectedKeys="selectedKeys"
    :treeData="treeData"
    :selectable="false"
  />
</template>
<script>
  import store from '@/store'

  export default {
    props: {
      defaultCheckedKeys: {
        type: Array,
        default: () => []
      }
    },
    data () {
      return {
        defaultExpandAll: true,
        checkedKeys: ['index'],
        selectedKeys: [],
        treeData: [],
        allPermissions: {}
      }
    },
    watch: {
      defaultCheckedKeys (permissions) {
        permissions.forEach(permission => {
          this.checkedKeys.push(permission.name)
        })
      }
    },
    created () {
      this.recursiveRouter(store.getters.addRouters, this.treeData)
    },
    methods: {
      onCheck (checkedKeys) {
        this.checkedKeys = checkedKeys
      },
      recursiveRouter (routers, treeData) {
        routers.forEach(router => {
          if (!router.hasOwnProperty('meta') ||
              (router.hasOwnProperty('meta') && !router.meta.hasOwnProperty('permission') && !router.hasOwnProperty('children')) ||
              router.hidden) {
            return true
          }

          var child = {
            title: router.meta.title,
            key: router.name
          }

          // 如果是必有权限 这里就加上 disable
          if (router.meta.hasOwnProperty('mustHavePermission') && router.meta.mustHavePermission) {
            child.disabled = true
          }

          if (router.hasOwnProperty('children') && router.children.length > 0) {
            child.children = []
            this.recursiveRouter(router.children, child.children)
          }

          // 存储 key => permission
          this.allPermissions[router.name] = router.meta.permission

          treeData.push(child)
        })
      },
      submit (result) {
        try {
          var checkedPermissions = []

          this.checkedKeys.forEach(key => {
            if (!this.allPermissions.hasOwnProperty(key) || this.allPermissions[key] === undefined) {
              return
            }
            this.allPermissions[key].forEach(permission => checkedPermissions.push(permission))
          })

          result(null, { permissions: checkedPermissions })
        } catch (e) {
          console.log(e)
        } finally {
        }
      }
    }
  }
</script>
